package pers.qianyu.backup.service.impl;

import cn.hutool.core.io.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.backup.pojo.*;
import pers.qianyu.backup.service.*;

import java.io.*;

/**
 * @author mizzle rain
 * @date 2020-10-27 13:47
 */
@Service("backupService")
public class MySQLBackupServiceImpl implements BackupService {
    @Autowired
    private BackupDataSourceProperties backupDataSourceProperties;

    @Override
    public boolean backup(String filePath) {
        File backupFile = new File(filePath);
        if (!backupFile.exists()) {
            FileUtil.touch(backupFile);
        }
        StringBuilder sb = new StringBuilder();
        sb.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");
        sb.append(" -h").append(backupDataSourceProperties.getHost())
                .append(" -u").append(backupDataSourceProperties.getUsername())
                .append(" -p").append(backupDataSourceProperties.getPassword());
        sb.append(" --result-file=")
                .append(filePath)
                .append(" --default-character-set=utf8 ")
                .append(backupDataSourceProperties.getDatabase());
        // 调用外部执行 exe 文件的 Java API
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(getCommand(sb.toString()));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        try {
            if (process.waitFor() == 0) {
                // 0 表示线程正常终止
                System.out.println("数据已经备份到 " + filePath + " 文件中");
                return true;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    public boolean restore(String filePath) {
        File restoreFile = new File(filePath);
        if (restoreFile.isDirectory()) {
            for (File file : FileUtil.loopFiles(restoreFile)) {
                if (file.exists() && file.getPath().endsWith(".sql")) {
                    filePath = file.getAbsolutePath();
                    break;
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("mysql -h").append(backupDataSourceProperties.getHost())
                .append(" -u").append(backupDataSourceProperties.getUsername())
                .append(" -p").append(backupDataSourceProperties.getPassword());
        sb.append(" ").append(backupDataSourceProperties.getDatabase())
                .append(" < ").append(filePath);
        try {
            Process process = Runtime.getRuntime().exec(getCommand(sb.toString()));
            if (process.waitFor() == 0) {
                System.out.println("数据已从 " + filePath + " 导入到数据库中");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static String[] getCommand(String command) {
        String os = System.getProperty("os.name");
        String shell = "/bin/bash";
        String c = "-c";
        if (os.toLowerCase().startsWith("win")) {
            shell = "cmd";
            c = "/c";
        }
        String[] cmd = {shell, c, command};
        return cmd;
    }
}
